// 使用 window 对象来存储状态，避免重复声明
if (!window.isContentScriptReady) {
  window.isContentScriptReady = true;
  
  // 等待页面完全加载
  function waitForPageLoad() {
    return new Promise((resolve) => {
      if (document.readyState === 'complete') {
        resolve();
      } else {
        window.addEventListener('load', resolve);
      }
    });
  }
  
  // 发送初始化消息
  chrome.runtime.sendMessage({ action: 'contentScriptReady' });
  
  function getExcalidrawData() {
    try {
      const excalidrawData = localStorage.getItem('excalidraw');
      const excalidrawState = localStorage.getItem('excalidraw-state');
      const excalidrawTheme = localStorage.getItem('excalidraw-theme');
      const elements = excalidrawData ? JSON.parse(excalidrawData) : [];
      
      // 解析 excalidraw-state
      const state = excalidrawState ? JSON.parse(excalidrawState) : {};
      
      const assembledData = {
        type: "excalidraw",
        version: 2,
        source: "https://excalidraw.com",
        elements: elements,
        appState: {
          gridSize: state.gridSize || 20,
          gridStep: state.gridStep || 5,
          gridModeEnabled: state.gridModeEnabled || false,
          viewBackgroundColor: state.viewBackgroundColor || "#ffffff"
        },
        files: {}
      };
  
      return {
        assembledData,
        rawState: excalidrawState,
        theme: excalidrawTheme
      };
    } catch (error) {
      console.error('获取数据时出错:', error);
      throw error;
    }
  }
  
  // 监听来自 popup 的消息
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'ping') {
      sendResponse({ status: 'ok' });
      return true;
    }
    
    if (request.action === "getExcalidrawData") {
      try {
        const data = getExcalidrawData();
        sendResponse(data);
      } catch (error) {
        sendResponse({ error: error.message });
      }
      return true;
    } else if (request.action === "setExcalidrawData") {
      // 确保页面加载完成后再设置数据
      waitForPageLoad().then(() => {
        try {
          // 对 elements 进行 UTF-8 编码处理
          const elementsString = JSON.stringify(request.data.elements, (key, value) => {
            if (typeof value === 'string') {
              return decodeURIComponent(escape(value));
            }
            return value;
          });
          
          // 获取现有的 state
          const currentState = localStorage.getItem('excalidraw-state');
          const state = currentState ? JSON.parse(currentState) : {};
          
          // 更新 state 中的关键值
          state.gridSize = request.data.appState.gridSize;
          state.gridStep = request.data.appState.gridStep;
          state.gridModeEnabled = request.data.appState.gridModeEnabled;
          state.viewBackgroundColor = request.data.appState.viewBackgroundColor;
          
          // 保存更新后的数据
          localStorage.setItem('excalidraw', elementsString);
          localStorage.setItem('excalidraw-state', JSON.stringify(state));
          
          window.location.reload();
          sendResponse({ success: true });
        } catch (error) {
          console.error('设置数据时出错:', error);
          sendResponse({ success: false, error: error.message });
        }
      });
      return true;
    }
  });
  
  console.log('Content script loaded!');
}

// 确认 content script 已加载
chrome.runtime.sendMessage({ action: "contentScriptLoaded" }); 